有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    您可以使用:

    Collections.replaceAll(list, "two", "one");
    

    the documentation

    Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)). (This method has no effect on the size of the list.)

    该方法还返回一个boolean,以指示是否实际进行了任何替换

    ^{}有更多的static实用方法,您可以在List上使用(例如sortbinarySearchshuffle等)


    片段

    下面展示了Collections.replaceAll的工作原理;它还显示,您还可以替换到null或从null替换:

        List<String> list = Arrays.asList(
            "one", "two", "three", null, "two", null, "five"
        );
        System.out.println(list);
        // [one, two, three, null, two, null, five]
    
        Collections.replaceAll(list, "two", "one");
        System.out.println(list);
        // [one, one, three, null, one, null, five]
    
        Collections.replaceAll(list, "five", null);
        System.out.println(list);
        // [one, one, three, null, one, null, null]
    
        Collections.replaceAll(list, null, "none");
        System.out.println(list);
        // [one, one, three, none, one, none, none]